<template>
  <div class="chat-room">
    <div class="back-button">
      <button @click="goBack">返回</button>
    </div>
    <h1>超时工单提醒</h1>
    <div class="user-controls">
      <input type="text" v-model="sendOutUser" placeholder="自己的用户名" ref="sendOutUser" />
      <button @click="connectWebSocket">上线</button>
      <button @click="closeWebSocket">下线</button>
      <span v-if="unreadCount > 0" class="unread-count">{{ unreadCount }} 未读消息</span>
    </div>

    <div class="message-input">
      <input type="text" v-model="msg" placeholder="要发送的信息" />
      <input type="text" v-model="receiveUser" placeholder="接收人的用户名" />
      <button @click="send">发送</button>
    </div>

    <!-- 手动分配按钮 -->
    <template>
      <el-button type="text" @click="manualAllocation">手动分配</el-button>
    </template>

    <hr />

    <div class="msg-list">
      <div v-for="(msg, index) in msgList" :key="index" class="msg">{{ msg }}</div>
    </div>

    <!-- 手动分配弹窗 -->
    <el-dialog title="手动分配" :visible.sync="dialogVisible" width="50%">
      <div class="input-container">
        <!-- 输入工单号的输入框 -->
        <input type="text" v-model="orderId" placeholder="请输入工单号" />
        <el-button type="primary" @click="confirmAllocation">确认</el-button>
      </div>
      <!-- 在线工作人员信息表格 -->
      <el-table :data="onlineStaffs" style="width: 100%" v-if="onlineStaffs.length > 0">
        <el-table-column prop="userId" label="ID" width="180"></el-table-column>
        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="allocateToStaff(scope.row)">确认分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TimeoutNotification",
  data() {
    return {
      websocket: null,
      sendOutUser: '',
      msg: '',
      receiveUser: '',
      msgList: [],
      unreadCount: 0,
      orderId: '', // 工单号
      RoleId: '',
      dialogVisible: false, // 控制弹窗显示/隐藏
      onlineStaffs: [] // 在线工作人员的信息
    };
  },
  methods: {
    // 打开手动分配弹窗
    manualAllocation() {
      this.dialogVisible = true;
    },
    // 确认工单号并获取在线工作人员信息
    confirmAllocation() {
      if (this.orderId === '') {
        this.$message.error('请输入工单号');
        return;
      }
      const formData = new FormData();
      formData.append('orderId', this.orderId);
     this.$http.post('/WebSocket/getOnlineUserIds',formData)
       .then(response => {
         console.log(response);

          this.onlineStaffs=response.data.data
       })
       .catch(error => {
         console.error(error);
       });


      // 这里需要调用后端接口来验证工单号
      // 如果验证通过,则获取在线工作人员的信息

    },
    // 获取在线工作人员信息

    // 分配工单给指定工作人员
    allocateToStaff(staff) {
      // 这里需要调用后端接口来完成工单分配
      const formData = new FormData();
        formData.append('orderId', this.orderId);
        formData.append('agentId', staff.userId);

        this.$http.post('/WebSocket/distributionOrder', formData)
          .then(response => {
            this.$message.success('工单分配成功');
            this.dialogVisible = false;
          })
          .catch(error => {
            console.error(error);
            this.$message.error('工单分配失败');
          });
    },
    goBack() {
      this.$router.go(-1);
    },
    connectWebSocket() {
      this.sendOutUser = localStorage.getItem('currentAccountName');
      if ('WebSocket' in window) {
        const token = localStorage.getItem("token");
        this.websocket = new WebSocket("ws://localhost:8877/web-socket/" + token);

        this.websocket.onerror = () => {
          alert("连接发生错误");
        };

        this.websocket.onopen = () => {
          this.$refs.sendOutUser.readOnly = true;
          this.$refs.sendOutUser.style.backgroundColor = '#ddd';
        };

        this.websocket.onmessage = (event) => {
          if (event.data.startsWith("未处理的工单:")) {
            const workOrderJson = event.data.replace("未处理的工单: ", "");
            const workOrder = JSON.parse(workOrderJson);
            this.msgList.push(`未读工单: ID ${workOrder.orderId}, 内容: ${workOrder.description}, 状态: ${workOrder.status}`);
            this.$message({
              message: `您有新的未读工单: ID ${workOrder.orderId}, 内容: ${workOrder.description}, 状态: ${workOrder.status}`,
              type: 'info'
            });
          } else if (event.data.startsWith("未读消息:")) {
            this.unreadCount += 1;
            this.msgList.push(event.data);
          } else {
            this.msgList.push(event.data);
          }
        };

        this.websocket.onclose = () => {
          this.msgList.push("websocket连接关闭");
        };

        window.onbeforeunload = () => {
          this.closeWebSocket();
        };
      } else {
        alert('当前浏览器不支持 websocket');
      }
    },
    closeWebSocket() {
      if (this.websocket) {
        this.websocket.close();
      }
    },
    send() {
      if (this.msg === "") {
        alert("请输入消息");
        return;
      }

      const m = new Map();
      m.set("sendOutUser", this.sendOutUser);
      m.set("msg", this.msg);

      if (this.receiveUser === "") {
        m.set("type", 0);
      } else {
        m.set("receiveUser", this.receiveUser);
        m.set("type", 1);
      }

      const json = this.mapToJson(m);
      this.websocket.send(json);
      this.msgList.push("我: " + this.msg);
      this.msg = '';
      if (this.RoleId !== 4 && this.RoleId !== '4') {
        this.Conversation = true;
      }
    },
    mapToJson(map) {
      const obj = Object.create(null);
      for (const [k, v] of map) {
        obj[k] = v;
      }
      return JSON.stringify(obj);
    }
  },
  created() {
    this.selectRoleId();
  },
};
</script>

<style scoped>
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
}

.back-button button {
  width: 80px;
  height: 36px;
  padding: 5px 10px;
  border-radius: 5px;
  background-color: #5cb85c;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 16px;
}

.back-button button:hover {
  background-color: #4cae4c;
}

.chat-room {
  max-width: 800px;
  margin: 30px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
  position: relative;
}

.user-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.message-input {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

input {
  width: 150px;
  height: 30px;
  line-height: 25px;
  padding: 5px 10px;
  border-radius: 5px;
  border: 2px solid #ccc;
  font-size: 16px;
  margin-right: 10px;
}

button {
  width: 80px;
  height: 36px;
  padding: 5px 10px;
  border-radius: 5px;
  background-color: #5cb85c;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 16px;
}

button:hover {
  background-color: #4cae4c;
}

.unread-count {
  margin-left: 10px;
  color: red;
  font-weight: bold;
}

hr {
  margin: 20px 0;
}

.msg-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e1e1e1;
  border-radius: 5px;
  padding: 10px;
  background: white;
}

.msg {
  padding: 5px;
  margin: 5px 0;
  border-radius: 5px;
  background-color: #e7f3fe;
  color: #31708f;
  word-wrap: break-word;
}
</style>
